"""
用户账户相关功能：注册、短信、登陆、注销...
"""
from django.http import JsonResponse
from django.shortcuts import render
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm


def register(request):
    """根据请求方式来判断 是访问页面 还是 提交注册"""
    print(request)
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    elif request.method == 'POST':
        # 提交注册
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return JsonResponse({'status': True, 'data': '/login/'})
        else:
            return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送短信"""
    form = SendSmsForm(request, data=request.GET)
    # from里面是定义了手机号的格式校验

    if form.is_valid():
        # 校验通过 且短信已经发送成功
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSmsForm(request.POST)
    if form.is_valid():
        # 用户登录成功 将用户信息放入session
        user_obj = form.cleaned_data['mobile_phone']
        # todo
        print(user_obj)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})
